package org.vnl.platform.impl.openjpa.std;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import org.apache.log4j.Logger;
import org.vnl.platform.job.IJob;
import org.vnl.platform.job.JobExecException;

/**
 * 設定在Tomacat中使用的TomcatEntityTransactionManager
 * @author Vaughan
 *
 */
public class TomcatEntityTransactionManagerSetupJob implements IJob {

    private static final Logger logger = Logger.getLogger(TomcatEntityTransactionManagerSetupJob.class);

    private static final String _PERSISTE_UNIT_NAMES = "PERSISTE_UNIT_NAMES";

    private Collection<String> punits;
    
    @SuppressWarnings("unchecked")
    @Override
    public void setParams(Map<String, ? extends Object> params) {
        Object obj = params.get(_PERSISTE_UNIT_NAMES);
        if (obj != null) {
            if (obj instanceof String) {
                punits = new ArrayList<String>();
                punits.add(obj.toString());
            } else if (obj instanceof Collection) {
                punits = (Collection<String>) obj;
            } else {
                punits = new ArrayList<String>();
            }
        }
        
    }

    @Override
    public int exec() throws JobExecException {
        if (punits == null) {
            return RESULT_SUCCESS;
        }
        for (String str : punits) {
            try {
                TomcatEntityTransactionManager.getInstance().addEntityManagerName(str);
                EntityTransactionManagerFactory.getInstance().setEntityTransactionManager(TomcatEntityTransactionManager.getInstance());
            } catch (RuntimeException e) {
                logger.fatal("Cannont setup Tomcat jpa transaction:" + str, e);
                System.out.println("Cannont Tomcat jpa transaction unit:" + str);
                e.printStackTrace();
                return RESULT_FAIL;
            }
        }
        return RESULT_SUCCESS;
    }

    @Override
    public void reset() throws JobExecException {
        TomcatEntityTransactionManager.getInstance().clear();
    }

}
